package cn.dapeng.common.nio;

import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NIOClient {

    public static void main(String[] args) throws Exception {
        sendFile("localhost", 8081, "D:\\rocketmq-5.1.0(启动脚本+控制台).zip");
    }

    public static void sendFile(String host, int port, String fileName) throws Exception {

        long startTime = System.currentTimeMillis();
        //socket套接字
        SocketChannel socketChannel = null;

        //FileChannel 文件读写、映射和操作的通道
        try (FileInputStream fileInputStream = new FileInputStream(fileName)) {
            FileChannel fileChannel = fileInputStream.getChannel();
            socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress(host, port));
            socketChannel.configureBlocking(true);

            long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);
            long endTime = System.currentTimeMillis();
            System.out.println("发送总字节数：" + transferCount + "耗时：" + (endTime - startTime) + " ms");
        } catch (Exception e) {
            System.err.println(e.getMessage());
        } finally {
            if (socketChannel != null) {
                socketChannel.close();
            }
        }
    }

}
